<template>
  <view>
    <view v-if="!orderAddresInfoShow && !payOrderShow">
      <!-- 头部导航栏 -->
      <view class="top-navigate bg-yellow flex" style="padding: 53px 10px 130px 10px;">
        <view class="content cuIcon-back text-xl top-navigate-title" @click="goBack"></view>
        <view class="text-xl order-title">万能帮买</view>
      </view>
      <!-- 下单 各种类型 区域-->
      <view class="buy-agent-order-info" :style="{'height':(tmpImgList.length>0? '400px':'320px')}">
        <!-- 标题 -->
        <view class="cu-bar bg-white" style="border-radius: 10px;">
          <view class="action sub-title">
            <text class="text-xl text-bold">概述你要买的商品</text>
            <text class="bg-yellow"></text>
          </view>
        </view>
        <!-- 商品内容区域 -->
        <view class="cu-form-group">
          <textarea maxlength="-1" placeholder="填写想代购的任意商品,如矿泉水2瓶..."
            v-model="orderInfo.goodsInfo.goodsDetail">
            </textarea>
        </view>
        <!-- 商品图显示区域 -->
        <form v-if="tmpImgList.length>0">
          <view class="cu-form-group">
            <view class="grid col-4 grid-square flex-sub">
              <view class="bg-img" v-for="(item,index) in tmpImgList" :key="index" @tap="ViewImage"
                :data-url="item">
                <image :src="item" mode="aspectFill" style="position: absolute;left:0"></image>
                <view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
                  <text class='cuIcon-close'></text>
                </view>
              </view>
              <view class="solids" @tap="uploadImg" v-if="tmpImgList.length<4">
                <text class='cuIcon-cameraadd'></text>
              </view>
            </view>
          </view>
        </form>
        <!-- 商品图 -->
        <view class="goods-pic">
          <view class="cuIcon-pic" @click="chooseImg">上传商品图</view>
          <view style="margin:0 5px;opacity: 0.3;">丨</view>
          <view class="example cuIcon-info" @click="showModal">填写示例</view>
        </view>
        <!-- 标签 -->
        <view class="goods-tag">
          <view class='cu-tag round' v-for="(item,index) in tagList" :key="index" @click="addTag(item)">
            {{item}}
          </view>
        </view>
        <!-- 注意点 -->
        <view class="order-tips cuIcon-info">
          禁止购买烟、药品以及法律法规明确禁止线上销售的医疗器械等;同时，未成年人禁止买酒。
        </view>
      </view>
      <!-- 购买地址 -->
      <view class="choose-buy-address" :style="{'height':(isDesignatedShop? '170px':'100px')}">
        <!-- 标题 -->
        <view class="cu-bar bg-white" style="border-radius: 10px;">
          <view class="action sub-title">
            <text class="text-xl text-bold">请选择购买地址</text>
            <text class="bg-yellow"></text>
          </view>
        </view>
        <!-- 选择框 -->
        <view class="check-address">
          <button class="buy-btn  shadow" :class="isDesignatedShop? 'line-yellow':'line-gray'"
            @click="changeAddress(0)">在指定店铺购买</button>
          <button class="buy-btn  shadow" :class="!isDesignatedShop? 'line-yellow':'line-gray'"
            @click="changeAddress(1)">骑手就近购买</button>
        </view>
        <!-- 指定店铺购买选择地址 -->
        <button class="cu-btn shop-address" @click="selectShopAddress" v-show="isDesignatedShop">
          <view class="cuIcon-usefullfill arrow-top"></view>
          <view class="cuIcon-location text-lg text-cut" :class="orderInfo.shopAddress.name? 'text-black':'text-grey'">
            {{orderInfo.shopAddress.name||'请选择购买店铺地址'}}
          </view>
        </button>
      </view>
      <!-- 收货地址 -->
      <view class="buy-delivery-address">
        <!-- 标题 -->
        <view class="cu-bar bg-white" style="border-radius: 10px;">
          <view class="action sub-title">
            <text class="text-xl text-bold">收货地址</text>
            <text class="bg-yellow"></text>
          </view>
        </view>
        <!-- 收货地址显示区域 -->
        <button class="cu-btn delivery-address" @click="editeOrderEndInfo">
          <view class="address-text">
            <text class="cuIcon-location text-lg text-black text-cut basis-xl margin-xs">
              {{addressEnd.name ||'填写收件地址'}}
            </text>
            <view class="cuIcon-right "></view>
          </view>
          <text class="text-sm text-red margin-xs">
            {{addressEnd.userName+addressEnd.phone||'填写联系人'}}
          </text>
        </button>
        <view class="cuIcon-time solid-top text-lg arrive-time">
          立即购买预计<text class="text-red"> {{orderInfo.receiveTime}}</text>送达
        </view>
      </view>
      <!-- 服务协议 -->
      <view class="service-agreement">
        <checkbox class='round orange' :class="checkbox?'checked':''" :checked="checkbox?true:false" value="false"
          @click="CheckboxChange"></checkbox>
        <text class="text-gray service-txt">已阅读并同意《帮送服务协议》</text>
      </view>
      <!-- 提交订单 -->
      <view class="cu-bar bg-white tabbar border shop foot">
        <view class="basis-lg" style="margin: 10px 15px;">
          <view class="flex">
            跑腿费 <text class="text-red text-xl">￥{{orderInfo.price}}</text>
          </view>
          <view class="distance">
            3公里内
          </view>
        </view>
        <button class="bg-red submit" @click="placeOrder">立即订购</button>
      </view>
      <!-- 底部隐藏的窗口 -->
      <view class="cu-modal bottom-modal" :class="modalName=='bottomModal'?'show':''">
        <view class="cu-dialog bg-white">
          <view class="cu-bar bg-white">
            <view class="action text-blue">点击示例，直接填写</view>
            <view class="action text-green cuIcon-close" @tap="hideModal"></view>
          </view>
          <!-- 示例 -->
          <view class="padding-sm goods-example" v-for="(item,index) in goodsExample" :key="index">
            <view class="basis-lg"><text style="float: left;">{{item}}</text> </view>
            <button class="cu-btn bg-white shadow" @click="addExample(item)">使用</button>
          </view>
        </view>
      </view>
    </view>
    <order-address-info v-if="orderAddresInfoShow"></order-address-info>
    <pay-order v-if="payOrderShow" :orderId="orderId" :price="orderInfo.price"></pay-order>
  </view>
</template>

<script>
  import {
    mapState,
    mapMutations,
  } from 'vuex'
  import getCurrentDateTime from '../../utils/currentTime.js'
  const db = uniCloud.database();
  export default {
    name: "buy-agent-order",
    data() {
      return {
        //订单信息
        orderInfo: {
          type:'代购',
          userId: '',
          deliveryAddress: {},
          shopAddress: {},
          goodsInfo: {
            imgList: [],
            goodsType: '',
            goodsDetail: '',
          },
          receiveTime: '10:15',
          //距离
          distance: '',
          price: 10
        },
        //临时商品图
        tmpImgList:[],
        goodsExample:["一次性口罩1包，矿泉水2瓶","苹果数据线1条","纸巾1包"],
        tagList: ["充电宝0", "充电宝1", "充电宝2", "充电宝3", "充电宝4", "充电宝5"],
        modalName: null,
        isDesignatedShop: true,
        //订单地址信息表单
        orderAddresInfoShow: false,
        orderAddresInfoShowFlag: 0,
        //服务协议checkbox
        checkbox: false,
        //支付订单组件显示
        payOrderShow: false,
        //当前下单的订单ID
        orderId: '',
      };
    },
    onLoad(options) {
      this.orderInfo.userId = this.userinfo._id
      this.orderInfo.deliveryAddress = this.addressEnd
      //获取时间
      const currentDateTime = getCurrentDateTime();
      console.log(currentDateTime); // 输出类似于 "2024-02-20 15:30:45"
      this.orderInfo.receiveTime=currentDateTime;
    },
    methods: {
      ...mapMutations('m_user', ['updateAddress']),
      goBack() {
        uni.navigateBack(-1)
      },
      addExample(item){
        this.orderInfo.goodsInfo.goodsDetail = this.orderInfo.goodsInfo.goodsDetail.concat('  ', item);
        this.hideModal();
      },
      //添加标签内容到商品描述
      addTag(item) {
        this.orderInfo.goodsInfo.goodsDetail = this.orderInfo.goodsInfo.goodsDetail.concat('  ', item)
      },
      // 隐藏底部弹框
      hideModal(e) {
        this.modalName = null
      },
      // 显示底部弹框
      showModal(e) {
        this.modalName = 'bottomModal'
      },
      changeAddress(num) {
        if (num > 0) {
          this.isDesignatedShop = false
          this.orderInfo.shopAddress = {}
        } else {
          this.isDesignatedShop = true
        }
      },
      //选择地址信息
      selectShopAddress() {
        uni.chooseLocation({
          success: (res) => {
            this.orderInfo.shopAddress = {
              address: res.address,
              latitude: res.latitude,
              longitude: res.longitude,
              name: res.name,
            };
          },
          fail: (err) => {
            uni.showToast({
              title: '获取位置失败'
            });
          }
        });
      },
      //编辑送取货订单终点位置信息
      editeOrderEndInfo() {
        this.orderAddresInfoShowFlag = 2
        this.orderAddresInfoShow = true
      },
      //服务协议点击更改勾选事件
      CheckboxChange() {
        this.checkbox = !this.checkbox
      },
      //点击上传商品图片事件
      chooseImg(){
        const that=this;
        uni.showActionSheet({
          itemList: ['从相册选择', '拍照'], // 显示的操作列表
          success: function(res) {
            if (!res.cancel) {
              if (res.tapIndex === 0) {
                // 用户选择了从相册选择
                uni.chooseImage({
                  count: 4, //默认9
                  sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
                  sourceType: ['album'], //从相册选择
                  success: (res) => {
                    console.log(res);
                    if (that.tmpImgList.length != 0) {
                      that.tmpImgList = that.tmpImgList.concat(res.tempFilePaths)
                    } else {
                      that.tmpImgList = res.tempFilePaths
                    }
                  }
                });
              } else if (res.tapIndex === 1) {
                // 用户选择了拍照
                uni.chooseImage({
                  count: 1,
                  sourceType: ['camera'], // 拍照
                  success: function (chooseRes) {
                    // 用户拍照后的处理逻辑
                    console.log(chooseRes.tempFilePaths);
                  }
                });
              }
            }
          }
        });
      },
      //上传图片操作
      async uploadImg() {
        // var date = this.date;
        // var time = this.time.replace(':', '-');  
        for (var i = 0; i < this.tmpImgList.length; i++) {
          let filePath = this.tmpImgList[i]
          //进行上传图片操作
          const result = await uniCloud.uploadFile({
            filePath: filePath,
            cloudPath:'buy-agent-img',
            cloudPath: 'buy-agent' + '-' + i + '.png',
          });
          this.orderInfo.goodsInfo.imgList.push(result.fileID)
        }
      },
      //删除商品图
      DelImg(e) {
        uni.showModal({
          title: this.userinfo.user_name,
          content: '确定要删除这张商品图片吗？',
          cancelText: '取消',
          confirmText: '确定',
          success: res => {
            if (res.confirm) {
              this.tmpImgList.splice(e.currentTarget.dataset.index, 1)
            }
          }
        })
      },
      //下单 添加订单事件回调
      async placeOrder() {
        if (this.orderInfo.goodsInfo.goodsDetail === '') return this.showModal()
        if (!this.checkbox) return uni.$showMsg('请先同意服务协议')
        //满足下单要求 将订单信息图片上传
        if(this.tmpImgList.length>0) await this.uploadImg();
        const {
          result: res
        } = await db.collection("my_order").add(this.orderInfo)
        //根据订单id 携带到子组件 支付订单
        this.orderId = res.id
        console.log('订单id：', this.orderId);
        if (res.id) {
          this.payOrderShow = true
          return uni.$showMsg('下单成功！')
        }
      }
    },
    computed: {
      ...mapState('m_user', ['userinfo', 'address', 'addressEnd']),
    },
    watch: {
      addressEnd(newValue, oldValue) {
        this.orderInfo.deliveryAddress = newValue
      }
    },
  }
</script>

<style lang="scss">
  .order-title {
    position: absolute;
    left: 50%;
    transform: translate(-50%, 0);
    font-weight: 700;
  }

  .cu-form-group textarea {
    margin: 0;
    font-size: 16px;
  }

  .buy-agent-order-info {
    top: -115px;
    position: relative;
    margin: 0 10px;
    background-color: white;
    border-radius: 10px;
    padding: 0 10px;

    .goods-pic {
      display: flex;
      justify-content: flex-end;
      margin: 10px;
    }

    .goods-tag {
      display: flex;
      flex-wrap: wrap;
    }

    .order-tips {
      margin: 10px 0;
      background-color: rgba(255, 144, 0, 0.3);
      border-radius: 10px;
      padding: 10px;
      color: darkorange;
    }
  }

  .goods-example{
    display: flex;
    width:92%;
    margin: auto;
    justify-content:space-around;
    align-items: center;
    border-bottom: 1px solid lightgrey;
  }

  .cu-tag {
    margin: 4px;
  }

  .cu-tag+.cu-tag {
    margin: 4px;
  }

  .choose-buy-address {
    top: -100px;
    position: relative;
    margin: 0 10px;
    height: 170px;
    background-color: white;
    border-radius: 10px;
    padding: 0 10px;

    .check-address {
      display: flex;
      justify-content: space-around;
      margin-bottom: 10px;

      .buy-btn {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        padding: 0 30rpx;
        font-size: 35rpx;
        height: 64rpx;
        line-height: 1;
        text-align: center;
        margin-left: initial;
        margin-right: initial;
      }
    }

    .shop-address {
      position: relative;
      height: 50px;
      display: flex;
      justify-content: left;
      align-items: center;
      border-radius: 10px;
      background-color: #f6f7f4;
      width: 92%;
      margin: 20px auto;

      .arrow-top {
        font-size: 20px;
        top: -15px;
        position: absolute;
        color: #f6f7f4;
        left: 40px;
      }
    }
  }

  //收货地址
  .buy-delivery-address {
    top: -85px;
    position: relative;
    margin: 0 10px;
    height: 180px;
    background-color: white;
    border-radius: 10px;
    padding: 0 10px;

    .delivery-address {
      height: 60px;
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      width: 92%;
      margin: auto;

      .address-text {
        display: flex;
        align-items: center;
      }
    }

    .arrive-time {
      color: black;
      width: 92%;
      margin: 10px auto;
      padding: 15px;
    }
  }

  .service-agreement {
    position: relative;
    margin: 20px auto;
    width: 95%;
    top: -90px;
    display: flex;
    align-items: center;

    .service-txt {
      margin-left: 10px;
      font-size: 14px;
    }
  }
</style>